package anagramUtils;


import exceptions.FileAccessException;
import exceptions.WrongPathFileException;

import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ReadFromFile {

    private FileInputStream fis;
    private DataInputStream dis;
    private BufferedReader br;

    public String[] readFile(String path) throws WrongPathFileException,
            FileAccessException {
        checkFile(path);
        String[] words;
        List<String> list = new ArrayList<String>();
        try {
            fis = new FileInputStream(path);
            dis = new DataInputStream(fis);
            br = new BufferedReader(new InputStreamReader(dis));
            String line;

            while ((line = br.readLine()) != null) {
                line = line.trim();
                if (line.length() != 0) {
                    words = line.replaceAll("[-+^,.]*", "").split("\\s");

                    list.addAll(Arrays.asList(words));
                    list.removeAll(Arrays.asList("", null));

                }
            }

        } catch (IOException e) {
            throw new FileAccessException("can not read file");
        } finally {
            if (br != null)
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (dis != null)
                try {
                    dis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            if (fis != null)
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
        }

        return list.toArray(new String[list.size()]);
    }

    private void checkFile(String path) throws WrongPathFileException,
            FileAccessException {
        File file = new File(path);

        if (file.isDirectory()) {
            throw new WrongPathFileException("File " + file.getName()
                    + " is directory!");
        }
        if (!file.exists()) {
            throw new WrongPathFileException("File " + file.getName()
                    + " does not exist");
        }
        if (!file.canRead()) {
            throw new FileAccessException("File " + file.getName()
                    + " is not readable");
        }
    }
}
